import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import { useRouter } from 'vue-router'

// 模拟数据
const mockRecordings = [
  {
    id: '1',
    name: '2023-11-05-14-30-00-main-stream.mp4',
    url: '/recordings/2023-11-05/14-30-00-main-stream.mp4',
    recording_url: 'http://10.168.60.122:8187/view/record/9/index.m3u8',
    start_time: '2023-11-05T14:30:00',
    end_time: '2023-11-05T16:30:00',
    duration: 7200,
    size: 1024 * 1024 * 1024, // 1GB
    stream_id: 'stream1',
    stream_name: '主直播间',
    task_id: 'task1',
    task_name: '日常直播任务',
    status: 'completed',
    screenshot_url: '/default-screenshot.jpg',
    file_count: 5,
    encoding_info: 'H.264',
    resolution: '1920x1080',
    bitrate: '3000kbps',
    node_id: 'node001',
    node_ip: '192.168.1.101',
    path: '/data/recordings/node001/2023-11-05/'
  },
  {
    id: '2',
    name: '2023-11-05-19-00-00-guest-stream.mp4',
    url: '/recordings/2023-11-05/19-00-00-guest-stream.mp4',
    recording_url: 'http://10.168.60.122:8187/view/record/9/index.m3u8',
    start_time: '2023-11-05T19:00:00',
    end_time: null,
    duration: 7200,
    size: 8589934592, // 8GB
    stream_id: 'stream2',
    stream_name: '嘉宾直播间',
    task_id: 'task2',
    task_name: '嘉宾访谈任务',
    status: 'recording',
    screenshot_url: '/default-screenshot.jpg',
    file_count: 3,
    encoding_info: 'H.265',
    resolution: '1280x720',
    bitrate: '2000kbps',
    node_id: 'node002',
    node_ip: '192.168.1.102',
    path: '/data/recordings/node002/2023-11-05/'
  },
  {
    id: '3',
    name: '2023-11-06-10-00-00-tech-stream.mp4',
    url: '/recordings/2023-11-06/10-00-00-tech-stream.mp4',
    recording_url: 'http://10.168.60.122:8187/view/record/9/index.m3u8',
    start_time: '2023-11-06T10:00:00',
    end_time: '2023-11-06T12:30:00',
    duration: 9000,
    size: 5368709120, // 5GB
    stream_id: 'stream1',
    stream_name: '主直播间',
    task_id: 'task1',
    task_name: '技术分享任务',
    status: 'completed',
    screenshot_url: '/default-screenshot.jpg',
    file_count: 4,
    encoding_info: 'H.264',
    resolution: '1920x1080',
    bitrate: '4000kbps',
    node_id: 'node001',
    node_ip: '192.168.1.101',
    path: '/data/recordings/node001/2023-11-06/'
  }
]

const mockClipTasks = [
  {
    id: 'clip1',
    name: '产品介绍片段',
    source_file: '2023-11-05-14-30-00-main-stream.mp4',
    stream_name: '主直播间',
    start_time: '2023-11-05T14:45:00',
    end_time: '2023-11-05T15:00:00',
    duration: 900,
    output_format: 'mp4',
    m3u8_url: 'http://example.com/hls/clips/clip1/index.m3u8',
    mp4_url: 'http://example.com/clips/clip1.mp4',
    status: 'completed',
    progress: 100,
    created_at: '2023-11-05T15:30:00',
    completed_at: '2023-11-05T15:35:00'
  },
  {
    id: 'clip2',
    name: '嘉宾问答环节',
    source_file: '2023-11-05-19-00-00-guest-stream.mp4',
    stream_name: '嘉宾直播间',
    start_time: '2023-11-05T19:15:00',
    end_time: '2023-11-05T19:45:00',
    duration: 1800,
    output_format: 'mp4',
    m3u8_url: '',
    mp4_url: '',
    status: 'processing',
    progress: 65,
    created_at: '2023-11-05T21:10:00',
    completed_at: null
  }
]

const mockStreams = [
  { id: 'stream1', name: '主直播间' },
  { id: 'stream2', name: '嘉宾直播间' }
]

const mockTasks = [
  { id: 'task1', name: '日常直播任务' },
  { id: 'task2', name: '嘉宾访谈任务' }
]

const mockTranscodeTemplates = [
  { id: 'template1', name: '高清模板', resolution: '1920x1080' },
  { id: 'template2', name: '标清模板', resolution: '1280x720' }
]

export function useRecordingClipping() {
  // 标签页状态
  const activeTab = ref('recordings')

  // 录制管理相关数据
  const recordings = ref([])
  const recordingLoading = ref(false)
  const streams = ref([])
  const tasks = ref([])
  const transcodeTemplates = ref([])

  // 录制管理筛选条件
  const recordingSearchKeyword = ref('')
  const recordingDateRange = ref([])
  const streamFilter = ref('')
  const taskFilter = ref('')

  // 录制管理分页
  const recordingCurrentPage = ref(1)
  const recordingPageSize = ref(20)
  const totalRecordings = ref(0)
  const totalSize = ref('0 MB')

  // 拆条任务相关数据
  const clipTasks = ref([])
  const clipLoading = ref(false)
  const totalClipTasks = ref(0)
  const processingClipTasks = ref(0)
  const activeRecordings = ref(2)
  const completedRecordings = ref(4)
  const completedClipTasks = ref(5)

  // 拆条任务筛选条件
  const clipSearchKeyword = ref('')
  const streamNameFilter = ref('')
  const statusFilter = ref('')
  const formatFilter = ref('')

  // 拆条任务分页
  const clipCurrentPage = ref(1)
  const clipPageSize = ref(20)

  // 拆条相关
  const showClipDialog = ref(false)
  const selectedRecording = ref(null)
  const clipping = ref(false)
  const clipForm = ref({
    name: '',
    startTime: null,
    endTime: null,
    format: 'mp4',
    transcodeTemplate: ''
  })

  // 文件列表弹窗
  const showFileDialog = ref(false)
  const currentFiles = ref([])
  const loadingFiles = ref(false)
  const currentRecording = ref(null)

  // 播放器相关 - 录制视频
  const showPlayer = ref(false)
  const currentVideo = ref(null)
  const recordingVideoPlayer = ref(null)
  const clipVideoPlayer = ref(null)

  // 播放器相关 - 拆条视频
  const showPreview = ref(false)
  const currentClip = ref(null)
  const previewVideoPlayer = ref(null)

  // 录制列表计算属性
  const displayedRecordings = computed(() => {
    let result = [...recordings.value]
    
    // 关键词搜索
    if (recordingSearchKeyword.value) {
      const keyword = recordingSearchKeyword.value.toLowerCase()
      result = result.filter(item => 
        item.name.toLowerCase().includes(keyword) ||
        item.url.toLowerCase().includes(keyword)
      )
    }
    
    // 日期范围过滤
    if (recordingDateRange.value && recordingDateRange.value.length === 2) {
      const [startDate, endDate] = recordingDateRange.value
      result = result.filter(item => {
        const itemDate = new Date(item.start_time)
        return itemDate >= startDate && itemDate <= endDate
      })
    }
    
    // 直播流过滤
    if (streamFilter.value) {
      result = result.filter(item => item.stream_id === streamFilter.value)
    }
    
    // 任务过滤
    if (taskFilter.value) {
      result = result.filter(item => item.task_id === taskFilter.value)
    }
    
    return result
  })

  // 拆条任务列表计算属性
  const displayedTasks = computed(() => {
    let result = [...clipTasks.value]
    
    // 关键词搜索
    if (clipSearchKeyword.value) {
      const keyword = clipSearchKeyword.value.toLowerCase()
      result = result.filter(item => 
        item.name.toLowerCase().includes(keyword) ||
        item.source_file.toLowerCase().includes(keyword)
      )
    }
    
    // 直播名称过滤
    if (streamNameFilter.value) {
      const keyword = streamNameFilter.value.toLowerCase()
      result = result.filter(item => 
        item.stream_name && item.stream_name.toLowerCase().includes(keyword)
      )
    }
    
    // 状态过滤
    if (statusFilter.value) {
      result = result.filter(item => item.status === statusFilter.value)
    }
    
    // 格式过滤
    if (formatFilter.value) {
      result = result.filter(item => item.output_format === formatFilter.value)
    }
    
    return result
  })

  // 获取状态类型
  const getStatusType = (status) => {
    switch (status) {
      case 'recording':
      case 'processing':
        return 'primary'
      case 'completed':
      case 'success':
        return 'success'
      case 'failed':
      case 'error':
        return 'danger'
      case 'pending':
        return 'warning'
      default:
        return 'info'
    }
  }

  // 获取状态文本
  const getStatusText = (status) => {
    const statusMap = {
      'recording': '录制中',
      'completed': '已完成',
      'failed': '失败',
      'processing': '处理中',
      'pending': '待处理'
    }
    return statusMap[status] || status
  }

  // 获取进度状态
  const getProgressStatus = (status) => {
    return status === 'processing' ? '' : 'success'
  }

  // 格式化日期时间
  const formatDateTime = (dateString) => {
    if (!dateString) return '-'
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }

  // 格式化文件大小
  const formatFileSize = (bytes) => {
    if (!bytes) return '0 B'
    if (bytes < 1024) return bytes + ' B'
    if (bytes < 1048576) return (bytes / 1024).toFixed(2) + ' KB'
    if (bytes < 1073741824) return (bytes / 1048576).toFixed(2) + ' MB'
    return (bytes / 1073741824).toFixed(2) + ' GB'
  }

  // 标签页切换处理
  const handleTabChange = (tabName) => {
    if (tabName === 'cliptasks') {
      fetchClipTasks()
    } else if (tabName === 'recordings') {
      fetchRecordings()
    }
  }

  // 获取录制列表
  const fetchRecordings = async () => {
    recordingLoading.value = true
    try {
      // 使用模拟数据替换API调用
      const filteredData = mockRecordings.filter(item => {
        let match = true
        if (recordingSearchKeyword.value) {
          const keyword = recordingSearchKeyword.value.toLowerCase()
          match = item.name.toLowerCase().includes(keyword) || item.url.toLowerCase().includes(keyword)
        }
        if (match && streamFilter.value) {
          match = item.stream_id === streamFilter.value
        }
        if (match && taskFilter.value) {
          match = item.task_id === taskFilter.value
        }
        if (match && recordingDateRange.value && recordingDateRange.value.length === 2) {
          const [startDate, endDate] = recordingDateRange.value
          const itemDate = new Date(item.start_time)
          match = itemDate >= startDate && itemDate <= endDate
        }
        return match
      })
      
      const totalSize = filteredData.reduce((sum, item) => sum + item.size, 0)
      
      recordings.value = filteredData
      totalRecordings.value = filteredData.length
      totalSize.value = formatFileSize(totalSize)
      
      // 同时设置直播流和任务列表的模拟数据
      streams.value = mockStreams
      tasks.value = mockTasks
      transcodeTemplates.value = mockTranscodeTemplates
    } catch (error) {
      ElMessage.error('获取录制列表失败')
    } finally {
      recordingLoading.value = false
    }
  }

  // 获取拆条任务列表
  const fetchClipTasks = async () => {
    clipLoading.value = true
    try {
      // 使用模拟数据替换API调用
      const filteredData = mockClipTasks.filter(item => {
        let match = true
        if (clipSearchKeyword.value) {
          const keyword = clipSearchKeyword.value.toLowerCase()
          match = item.name.toLowerCase().includes(keyword) || item.source_file.toLowerCase().includes(keyword)
        }
        if (match && streamNameFilter.value) {
          const keyword = streamNameFilter.value.toLowerCase()
          match = item.stream_name && item.stream_name.toLowerCase().includes(keyword)
        }
        if (match && statusFilter.value) {
          match = item.status === statusFilter.value
        }
        if (match && formatFilter.value) {
          match = item.output_format === formatFilter.value
        }
        return match
      })
      
      clipTasks.value = filteredData
      totalClipTasks.value = filteredData.length
      processingClipTasks.value = filteredData.filter(task => task.status === 'processing').length
    } catch (error) {
      ElMessage.error('获取拆条任务列表失败')
    } finally {
      clipLoading.value = false
    }
  }

  // 获取直播流列表
  const fetchStreams = async () => {
    try {
      const response = await api.streams.list({ page: 1, pageSize: 1000 })
      streams.value = response.data
    } catch (error) {
      console.error('获取直播流列表失败', error)
    }
  }

  // 获取任务列表
  const fetchTasks = async () => {
    try {
      const response = await api.tasks.list({ page: 1, pageSize: 1000 })
      tasks.value = response.data
    } catch (error) {
      console.error('获取任务列表失败', error)
    }
  }

  // 获取转码模板
  const fetchTranscodeTemplates = async () => {
    try {
      const response = await api.transcodeTemplates.list()
      transcodeTemplates.value = response.data
    } catch (error) {
      console.error('获取转码模板失败', error)
    }
  }

  // 录制搜索处理
  const handleRecordingSearch = () => {
    recordingCurrentPage.value = 1
    fetchRecordings()
  }

  // 录制日期变化处理
  const handleRecordingDateChange = () => {
    recordingCurrentPage.value = 1
    fetchRecordings()
  }

  // 拆条任务搜索处理
  const handleClipSearch = () => {
    clipCurrentPage.value = 1
    fetchClipTasks()
  }

  // 刷新录制数据
  const refreshRecordingData = () => {
    fetchRecordings()
  }

  // 刷新拆条数据
  const refreshClipData = () => {
    fetchClipTasks()
  }

  // 录制分页处理
  const handleRecordingSizeChange = (size) => {
    recordingPageSize.value = size
    fetchRecordings()
  }

  const handleRecordingCurrentChange = (current) => {
    recordingCurrentPage.value = current
    fetchRecordings()
  }

  // 拆条分页处理
  const handleClipSizeChange = (size) => {
    clipPageSize.value = size
    fetchClipTasks()
  }

  const handleClipCurrentChange = (current) => {
    clipCurrentPage.value = current
    fetchClipTasks()
  }

  // 使用路由
  const router = useRouter()
  
  // 开始拆条
  const startClip = (recording) => {
    selectedRecording.value = recording
    clipForm.value = {
      name: `${recording.name}_拆条_${new Date().toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-').replace(/:/g, '-')}`,
      startTime: null,
      endTime: null,
      format: 'mp4',
      transcodeTemplate: ''
    }
    // 重定向到独立拆条页面
    router.push({ name: 'RecordingClippingPage', params: { id: recording.id } })
  }

  // 重置拆条表单
  const resetClipForm = () => {
    selectedRecording.value = null
    clipForm.value = {
      name: '',
      startTime: null,
      endTime: null,
      format: 'mp4',
      transcodeTemplate: ''
    }
  }

  // 更新开始时间
  const updateStartTime = () => {
    // 可以在这里添加验证逻辑
  }

  // 更新结束时间
  const updateEndTime = () => {
    // 可以在这里添加验证逻辑
  }

  // 提交拆条任务
  const submitClip = async () => {
    if (!clipForm.value.name) {
      ElMessage.warning('请输入拆条名称')
      return
    }
    
    if (!clipForm.value.startTime || !clipForm.value.endTime) {
      ElMessage.warning('请选择开始时间和结束时间')
      return
    }
    
    clipping.value = true
    try {
      const response = await api.clipTasks.create({
        name: clipForm.value.name,
        sourceFile: selectedRecording.value.recording_url,
        startTime: clipForm.value.startTime,
        endTime: clipForm.value.endTime,
        format: clipForm.value.format,
        transcodeTemplate: clipForm.value.transcodeTemplate,
        streamName: selectedRecording.value.name
      })
      
      ElMessage.success('拆条任务创建成功')
      showClipDialog.value = false
      resetClipForm()
      
      // 自动切换到拆条任务标签页并刷新列表
      activeTab.value = 'cliptasks'
      fetchClipTasks()
    } catch (error) {
      ElMessage.error('拆条任务创建失败')
    } finally {
      clipping.value = false
    }
  }

  // 播放视频
  const playVideo = (recording) => {
    currentVideo.value = recording
    showPlayer.value = true
  }

  // 关闭播放器
  const closePlayer = () => {
    currentVideo.value = null
  }

  // 播放器准备就绪
  const onPlayerReady = () => {
    console.log('播放器准备就绪')
  }

  // 播放器错误
  const onPlayerError = (error) => {
    ElMessage.error('视频播放失败')
    console.error('播放器错误', error)
  }

  // 显示文件列表
  const showFileList = async (recording) => {
    currentRecording.value = recording
    loadingFiles.value = true
    try {
      const response = await api.recordings.getFiles(recording.id)
      currentFiles.value = response.data
      showFileDialog.value = true
    } catch (error) {
      ElMessage.error('获取文件列表失败')
    } finally {
      loadingFiles.value = false
    }
  }

  // 下载文件
  const downloadFile = (file) => {
    try {
      window.open(file.url, '_blank')
    } catch (error) {
      ElMessage.error('下载失败')
    }
  }

  // 删除文件
  const deleteFile = async (file) => {
    try {
      await ElMessageBox.confirm('确定要删除该文件吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await api.recordings.deleteFile(file.id)
      ElMessage.success('文件删除成功')
      
      // 重新获取文件列表
      if (currentRecording.value) {
        await showFileList(currentRecording.value)
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('文件删除失败')
      }
    }
  }

  // 切换录制状态
  const toggleRecording = async (recording) => {
    try {
      if (recording.status === 'recording') {
        await api.recordings.stop(recording.id)
        ElMessage.success('录制已停止')
      } else {
        await api.recordings.start(recording.id)
        ElMessage.success('录制已开始')
      }
      fetchRecordings()
    } catch (error) {
      ElMessage.error(recording.status === 'recording' ? '停止录制失败' : '开始录制失败')
    }
  }

  // 显示录制详情
  const showInfo = (recording) => {
    // 可以显示更详细的录制信息
    ElMessageBox.alert(`
      直播名称: ${recording.name}
      录制URL: ${recording.recording_url || '-'}
      开始时间: ${formatDateTime(recording.start_time)}
      结束时间: ${formatDateTime(recording.end_time)}
      状态: ${getStatusText(recording.status)}
      文件个数: ${recording.file_count || 0}
    `, '录制详情')
  }

  // 预览拆条视频
  const previewClip = (clipTask) => {
    currentClip.value = clipTask
    showPreview.value = true
  }

  // 下载拆条视频
  const downloadClip = (clipTask) => {
    try {
      window.open(clipTask.output_path, '_blank')
    } catch (error) {
      ElMessage.error('下载失败')
    }
  }

  // 删除拆条任务
  const deleteTask = async (clipTask) => {
    try {
      await ElMessageBox.confirm('确定要删除该拆条任务吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await api.clipTasks.delete(clipTask.id)
      ElMessage.success('拆条任务删除成功')
      fetchClipTasks()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('拆条任务删除失败')
      }
    }
  }

  // 从API获取统计数据
  const fetchStats = async () => {
    try {
      // 实际项目中这里会调用API获取真实数据
      // const response = await api.recordingClipping.getStats()
      // totalRecordings.value = response.totalRecordings || 100
      // completedRecordings.value = response.completedRecordings || 85
      // activeRecordings.value = response.activeRecordings || 15
      // totalClipTasks.value = response.totalClipTasks || 20
      // completedClipTasks.value = response.completedClipTasks || 17
      // processingClipTasks.value = response.processingClipTasks || 3
      
      // 模拟数据，实际应从API获取
      totalRecordings.value = 100
      completedRecordings.value = 85
      activeRecordings.value = 15
      totalClipTasks.value = 20
      completedClipTasks.value = 17
      processingClipTasks.value = 3
    } catch (error) {
      console.error('获取统计数据失败:', error)
    }
  }

  // 组件挂载时初始化数据
  onMounted(async () => {
    // 先获取基本数据结构
    await fetchRecordings()
    await fetchClipTasks()
    // 确保统计数据在其他数据加载后设置，以覆盖mock数据计算的结果
    fetchStats()
  })

  return {
    // 状态
    activeTab,
    
    // 录制管理
    recordings,
    recordingLoading,
    streams,
    tasks,
    transcodeTemplates,
    recordingSearchKeyword,
    recordingDateRange,
    streamFilter,
    taskFilter,
    recordingCurrentPage,
    recordingPageSize,
    totalRecordings,
    totalSize,
    completedRecordings,
    activeRecordings,
    
    // 拆条任务
    clipTasks,
    clipLoading,
    totalClipTasks,
    processingClipTasks,
    completedClipTasks,
    clipSearchKeyword,
    streamNameFilter,
    statusFilter,
    formatFilter,
    clipCurrentPage,
    clipPageSize,
    
    // 对话框状态
    showClipDialog,
    selectedRecording,
    clipping,
    clipForm,
    showFileDialog,
    currentFiles,
    loadingFiles,
    currentRecording,
    showPlayer,
    currentVideo,
    recordingVideoPlayer,
    clipVideoPlayer,
    showPreview,
    currentClip,
    previewVideoPlayer,
    
    // 计算属性
    displayedRecordings,
    displayedTasks,
    
    // 工具函数
    getStatusType,
    getStatusText,
    getProgressStatus,
    formatDateTime,
    formatFileSize,
    
    // 方法
    handleTabChange,
    fetchRecordings,
    fetchClipTasks,
    fetchStreams,
    fetchTasks,
    fetchTranscodeTemplates,
    handleRecordingSearch,
    handleRecordingDateChange,
    handleClipSearch,
    refreshRecordingData,
    refreshClipData,
    handleRecordingSizeChange,
    handleRecordingCurrentChange,
    handleClipSizeChange,
    handleClipCurrentChange,
    startClip,
    resetClipForm,
    updateStartTime,
    updateEndTime,
    submitClip,
    playVideo,
    closePlayer,
    onPlayerReady,
    onPlayerError,
    showFileList,
    downloadFile,
    deleteFile,
    toggleRecording,
    showInfo,
    previewClip,
    downloadClip,
    deleteTask
  }
}